package com.fbt.transfer.app.driver.ui.index;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.activity.OrderDetailActivity;
import com.fbt.transfer.app.driver.model.OrderStatusEnum;
import com.fbt.transfer.app.driver.model.OrderTypeEnum;
import com.fbt.transfer.app.driver.model.index.OrderUnitVo;
import com.fbt.transfer.app.driver.util.Constants;
import com.permissionx.guolindev.PermissionX;
import com.fbt.transfer.app.driver.baidu.BaiDuLocationUtil;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

public class OrderInfoAdapter extends RecyclerView.Adapter<OrderInfoAdapter.OrderViewHolder> {

  static Map<OrderStatusEnum, String> statusMap = new EnumMap<>(OrderStatusEnum.class) {{
    put(OrderStatusEnum.CHANGE_OTHER_DRIVER, "开始服务");
    put(OrderStatusEnum.TAKE_ORDER, "开始服务");
    put(OrderStatusEnum.GO_TO_START, "出发接乘客");
    put(OrderStatusEnum.WAIT_FOR_PASSENGER, "已就位");
    put(OrderStatusEnum.ON_CAR, "行程中");
    put(OrderStatusEnum.FINISHED, "订单结束");
  }};

  // 复制到剪贴板的辅助方法
  private void copyToClipboard (Context context, String label, String text) {
    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText(label, text);
    clipboard.setPrimaryClip(clip);
  }

  // 显示Toast提示的辅助方法
  private void showToast (Context context, String message) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }

  private List<OrderUnitVo> orderList;
  private final Context context;
  private final Fragment fragment;
  private OnItemClickListener onItemClickListener;

  public interface OnItemClickListener {

    void onItemClick (OrderUnitVo order, int position);
  }

  public OrderInfoAdapter (Fragment fragment, Context context) {
    this.context = context;
    this.fragment = fragment;
    this.orderList = new ArrayList<>();
    this.onItemClickListener = null;
  }

  public void setOnItemClickListener (OnItemClickListener listener) {
    this.onItemClickListener = listener;
  }

  public void setData (List<OrderUnitVo> orders) {
    this.orderList = orders == null ? new ArrayList<>() : orders;
    notifyDataSetChanged();
  }

  public void addData (List<OrderUnitVo> orders) {
    if (orders != null && !orders.isEmpty()) {
      int startPosition = orderList.size();
      this.orderList.addAll(orders);
      notifyItemRangeInserted(startPosition, orders.size());
    }
  }

  @NonNull
  @Override
  public OrderViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);
    return new OrderViewHolder(view);
  }

  @Override
  public void onBindViewHolder (@NonNull OrderViewHolder holder, int position) {
    OrderUnitVo order = orderList.get(position);
    // 订单卡片的需要醒目一点的信息
    String bookTimeStr = order.getBookTime();
    holder.tvBookTime.setText(bookTimeStr);

    LocalDateTime bookTime = LocalDateTimeUtil.parse(bookTimeStr, Constants.DATE_YYYY_MM_DD_HH_MM);
    LocalDate bookDate = bookTime.toLocalDate();
    LocalDate today = LocalDate.now();
    if (
        today.isAfter(bookDate) &&
            bookDate.until(today, ChronoUnit.DAYS) == 1) {
      holder.tvBookTime.setText("昨天 " +
                                    LocalDateTimeUtil.format(bookTime, Constants.TIME_HH_MM));
    } else if (bookDate.isEqual(today)) {
      holder.tvBookTime.setText("今天 " +
                                    LocalDateTimeUtil.format(bookTime, Constants.TIME_HH_MM));
    } else if (today.until(bookDate, ChronoUnit.DAYS) == 1) {
      holder.tvBookTime.setText("明天 " +
                                    LocalDateTimeUtil.format(bookTime, Constants.TIME_HH_MM));
    } else if (today.until(bookDate, ChronoUnit.DAYS) == 2) {
      holder.tvBookTime.setText("后天 " +
                                    LocalDateTimeUtil.format(bookTime, Constants.TIME_HH_MM));
    }
    OrderTypeEnum orderType = order.getOrderType().convertOrderType();
    holder.tvOrderType.setText(orderType.getDesc());
    holder.tvOrderType.setBackgroundResource(
        OrderTypeEnum.PICK_UP == orderType ?
            R.drawable.jie_order_type_bg
            : R.drawable.song_order_type_bg
    );
    holder.tvCarGrade.setText(order.getBookCarGrade().getDesc());
    holder.tvOrderMileage.setText(
        String.format(
            "预计里程%s公里 耗时%s",
            order.getEstimateMileage().stripTrailingZeros().toPlainString(),
            CharSequenceUtil.trimToEmpty(order.getEstimateTime())
        )
    );
    // 设置订单号和复制功能
    String orderId = order.getId();
    holder.tvOrderId.setText("订单号：" + orderId);
    holder.ivCopyOrderId.setOnClickListener(v -> {
      copyToClipboard(v.getContext(), "订单号", orderId);
      showToast(v.getContext(), "订单号已复制");
    });

    // 设置订单金额
    BigDecimal income = order.getIncome();
    if (income.compareTo(BigDecimal.ZERO) > 0) {
      holder.tvOrderIncome.setVisibility(View.VISIBLE);
      holder.tvOrderIncome.setText(order.getIncome().toPlainString());
    } else {
      holder.tvOrderIncome.setVisibility(View.GONE);
    }

    // 设置订单来源
    holder.tvOrderSource.setVisibility(View.VISIBLE);
    holder.tvOrderSource.setText(order.getSource());

    // 设置手机号
    holder.tvPhoneNumber.setVisibility(View.VISIBLE);
    holder.tvPhoneNumber.setText(order.getPhone());

    holder.tvStartAddress.setText(order.getStartPosition().getDetail());
    holder.tvEndAddress.setText(order.getEndPosition().getDetail());
    // 根据订单状态设置显示
    OrderStatusEnum orderStatus = OrderStatusEnum.getByValue(order.getStatus());

    holder.layoutFlight.setVisibility(orderType == OrderTypeEnum.PICK_UP ? View.VISIBLE : View.GONE);
    if (orderType == OrderTypeEnum.PICK_UP) {
      holder.tvFlightNo.setText(order.getFlightNo());
      holder.tvFlightDate.setText(order.getFlightDate());
      holder.ivCopyFlightNo.setOnClickListener(v -> {
        copyToClipboard(v.getContext(), "航班号", order.getFlightNo());
        showToast(v.getContext(), "航班号已复制");
      });
    }

    holder.btnOrderStatus.setText(orderStatus.isCancel() ? "已取消" :
        statusMap.getOrDefault(orderStatus, "未知状态")
    );
    
    // 为订单状态按钮添加点击事件
    holder.btnOrderStatus.setOnClickListener(v -> {
      // 添加点击动画效果
      checkLocationPermissionAndNavigate(v.getContext(), order);
    });
    
    
    // Populate tags_layout with order tags
    LinearLayout tagsLayout = holder.itemView.findViewById(R.id.tags_layout);
    tagsLayout.setVisibility(View.GONE);
    tagsLayout.removeAllViews();
    if (order.getTags() != null) {
      tagsLayout.setVisibility(View.VISIBLE);
      for (String tag : order.getTags()) {
        TextView tagView = new TextView(context);
        tagView.setText(tag);
        tagView.setTextColor(context.getColor(R.color.blue));
        tagView.setBackgroundResource(R.drawable.bg_tag);
        tagView.setPadding(8, 4, 8, 8);
        // 设置 LayoutParams 并添加右边距 4dp
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.rightMargin = context.getResources().getDimensionPixelSize(R.dimen.spacing_4dp); // 4dp
        tagView.setLayoutParams(params);
        tagsLayout.addView(tagView);
      }
    }
    holder.ivCallIcon.setOnClickListener(v -> {
      // 获取电话号码，建议从数据模型中获取
      String phoneNumber = order.getPhone(); // 假设orderInfo包含司机电话

      if (TextUtils.isEmpty(phoneNumber)) {
        Toast.makeText(context, "电话号码不可用", Toast.LENGTH_SHORT).show();
        return;
      }
      // 调用拔打电话，先检查有没有拔打电话的权限，没有就申请
      List<String> permissions = new ArrayList<>();
      if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
          != PackageManager.PERMISSION_GRANTED) {
        permissions.add(Manifest.permission.CALL_PHONE);
      }
      if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
          != PackageManager.PERMISSION_GRANTED) {
        permissions.add(Manifest.permission.READ_CONTACTS);
      }
      if (permissions.isEmpty()) {
        // 有权限，直接拨打电话
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
        context.startActivity(intent);
      } else {
        // 申请权限
        PermissionX.init(fragment)
            .permissions(permissions)
            .explainReasonBeforeRequest()
            .onExplainRequestReason((scope, deniedList) ->
                                        scope.showRequestReasonDialog(
                                            deniedList, "该操作依赖于拔打电话、读取联系的权限", "我已明白",
                                            "拒绝"
                                        ))
            .request((allGranted, grantedList, deniedList) -> {
              if (allGranted) {
                // 权限授予则拨打电话
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
                context.startActivity(intent);
              } else {
                Toast.makeText(context, "拨打电话的权限被拒绝", Toast.LENGTH_SHORT).show();
              }
            });
      }
    });
  }
  
  
  /**
   * 检查位置权限和GPS状态，然后导航到订单详情页面
   */
  private void checkLocationPermissionAndNavigate(Context context, OrderUnitVo order) {
    // 检查GPS是否开启
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
    if (!gpsEnabled && !networkEnabled) {
      // GPS和网络定位都未开启，提示用户开启
      Toast.makeText(context, "请开启GPS或网络定位服务", Toast.LENGTH_SHORT).show();
      // 跳转到位置设置页面
      Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      context.startActivity(intent);
      return;
    }
    
    // 检查位置权限
    List<String> permissions = new ArrayList<>();
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
        != PackageManager.PERMISSION_GRANTED) {
      permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) 
        != PackageManager.PERMISSION_GRANTED) {
      permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    //todo 可能 不需要该权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
      if (!Environment.isExternalStorageManager()) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
        context.startActivity(intent);
        return;
      }
    }
    if (permissions.isEmpty()) {
      // 已有权限，获取位置并跳转
      getLocationAndNavigate(context, order);
    } else {
      // 申请权限
      PermissionX.init(fragment)
          .permissions(permissions)
          .explainReasonBeforeRequest()
          .onExplainRequestReason((scope, deniedList) ->
              scope.showRequestReasonDialog(
                  deniedList, "需要位置权限来显示地图和导航信息", "我已明白", "拒绝"
              ))
          .request((allGranted, grantedList, deniedList) -> {
            if (allGranted) {
              // 权限授予，获取位置并跳转
              getLocationAndNavigate(context, order);
            } else {
              Toast.makeText(context, "未授予位置权限，无法显示地图和导航信息", Toast.LENGTH_SHORT).show();
              // 即使没有权限也跳转到详情页面，但可能无法显示地图
              OrderDetailActivity.start(context, order);
            }
          });
    }
  }
  
  /**
   * 获取位置并导航到订单详情页面
   */
  private void getLocationAndNavigate(Context context, OrderUnitVo order) {
    // 获取百度定位实例并开始定位
    BaiDuLocationUtil locationUtil = BaiDuLocationUtil.getInstance();
    locationUtil.startLocation(true);
    // 检查是否已有位置信息
    if (BaiDuLocationUtil.locations != null) {
      // 已有位置信息，直接跳转
      OrderDetailActivity.start(context, order);
    } else {
      // 显示加载提示
      Toast.makeText(context, "正在获取位置信息...", Toast.LENGTH_SHORT).show();
      
      // 等待一段时间后检查位置信息
      new Handler().postDelayed(() -> {
        if (BaiDuLocationUtil.locations != null) {
          // 获取到位置信息，跳转
          OrderDetailActivity.start(context, order);
        } else {
          // 获取位置信息失败，提示用户
          Toast.makeText(context, "获取位置信息失败，请检查GPS和网络设置", Toast.LENGTH_SHORT).show();
          // 仍然跳转到详情页面，但可能无法显示当前位置
         OrderDetailActivity.start(context, order);
        }
      }, 3000); // 等待3秒
    }
  }

  @Override
  public int getItemCount () {
    return orderList.size();
  }

  static class OrderViewHolder extends RecyclerView.ViewHolder {

    TextView tvBookTime;
    TextView tvCarGrade;
    TextView tvStartAddress;
    TextView tvEndAddress;
    AppCompatButton btnOrderStatus;
    TextView tvOrderType;
    TextView tvOrderId;
    TextView tvOrderMileage;
    TextView tvOrderIncome;
    TextView tvOrderSource;
    TextView tvPhoneNumber;
    TextView tvFlightNo;
    TextView tvFlightDate;
    LinearLayout layoutFlight;
    ImageView ivCallIcon;
    ImageView ivCopyOrderId;
    ImageView ivCopyFlightNo;

    public OrderViewHolder (@NonNull View itemView) {
      super(itemView);
      tvBookTime = itemView.findViewById(R.id.tv_book_time);
      tvCarGrade = itemView.findViewById(R.id.tv_car_grade);
      tvStartAddress = itemView.findViewById(R.id.tv_start_address);
      tvEndAddress = itemView.findViewById(R.id.tv_end_address);
      btnOrderStatus = itemView.findViewById(R.id.btn_order_status);
      tvOrderType = itemView.findViewById(R.id.tv_order_type_desc);
      layoutFlight = itemView.findViewById(R.id.flight_layout);
      tvOrderId = itemView.findViewById(R.id.tv_order_id);
      tvOrderMileage = itemView.findViewById(R.id.tv_order_mileage);
      tvOrderIncome = itemView.findViewById(R.id.tv_order_income);
      tvOrderSource = itemView.findViewById(R.id.tv_order_source);
      tvPhoneNumber = itemView.findViewById(R.id.tv_phone_number);
      ivCallIcon = itemView.findViewById(R.id.iv_call_icon);
      ivCopyOrderId = itemView.findViewById(R.id.iv_copy_order_id);
      ivCopyFlightNo = itemView.findViewById(R.id.iv_copy_flight_no);
      tvFlightNo = itemView.findViewById(R.id.tv_flight_no);
      tvFlightDate = itemView.findViewById(R.id.tv_flight_date);
    }
  }
}